package mn.idax.exchange.otc.service.impl;

import mn.idax.exchange.common.CalendarUtil;
import mn.idax.exchange.otc.entity.Account;
import mn.idax.exchange.otc.entity.AccountHistory;
import mn.idax.exchange.otc.entity.OTCOrder;
import mn.idax.exchange.otc.enums.response.OrderResponseEnum;
import mn.idax.exchange.otc.exception.IdaxException;
import mn.idax.exchange.otc.mapper.AccountHistoryMapper;
import mn.idax.exchange.otc.service.AccountHistoryService;
import mn.idax.exchange.otc.service.AccountService;
import mn.idax.exchange.otc.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Create by jack_huang on 2018/8/20
 */
@Service
public class AccountHistoryServiceImpl implements AccountHistoryService {


    @Autowired
    private AccountService accountService;

    @Autowired
    private AccountHistoryMapper accountHistoryMapper;

    @Override
    public int insertAccountHistory(OTCOrder order, Integer userId) {

        AccountHistory accountHistory = new AccountHistory();

        Account account = accountService.getAccountByCoinIdAndUserId(userId, order.getCoinid());
        if (account == null){
            throw new IdaxException(OrderResponseEnum.ACCOUNT_ISNOTEXOST.getRespCode());
        }
        accountHistory.setCoinid(order.getCoinid());
        accountHistory.setAvailableamount(account.getAvailableamount().add(order.getQty()));
        accountHistory.setFrozenamount(account.getFrozenamount().subtract(order.getQty()));
        accountHistory.setSumamount(accountHistory.getAvailableamount().add(accountHistory.getFrozenamount()));
        accountHistory.setCreatetime(DateUtils.getCalendarToDate(CalendarUtil.getUTCDate(new Date())));
        accountHistory.setUpdatetime(accountHistory.getCreatetime());

        return accountHistoryMapper.insertSelective(accountHistory);
    }
}
